
import 'package:flutter/material.dart';
import 'package:shimmer/shimmer.dart';
import 'package:xim/common/style/colors.dart';
import 'package:xim/common/util/device.dart';
import 'package:xim/http/http.dart';
import 'package:xim/router/index.dart';


/// 页面加载蒙版
mixin ShimmerState<T extends StatefulWidget> on State<T>, AppBarMixin {

  @override
  List<Widget> get appBarActions => [
    IconButton(onPressed: () {
    }, icon: const Icon(Icons.more_horiz,))
  ];

  @override
  TextStyle get appBarTitleStyle => const TextStyle();

  @override
  IconThemeData get iconTheme => IconThemeData(
    color: highlightColor,
  );

  /// 数据初始化完成
  bool _isInitSuccess = false;

  /// 超时时间 default 60s
  Duration get loadingTimeout => Duration(seconds: requestTimeout);

  DateTime startTime = DateTime.now();

  bool _isTimeout = false;

  /// 加载文字提示
  String get loadingHintText => "正在加载...";

  Color get highlightColor => Colors.grey;


  /// 加载文字提示样式
  TextStyle get loadingHintTextStyle => const TextStyle(
      fontSize: 18.0,
      color: Colors.grey
  );

  @override
  Color get appBarBgColor => Colors.transparent;

  @override
  double get elevation => 0;

  Widget get timeoutWidget => Container(
    color: _shimmerBgColorNotifier.value.color,
    child: Column(
      children: [
        appBar,
        Expanded(
          child: GestureDetector(
            onTap: (){
              // 重试
              setState(() {
                _isTimeout = false;
                // 重新加载
                if(context.mounted){
                  _init();
                  router.refresh();
                }
              });
            },
            child: Container(
              color: Colors.transparent,
              child: Center(
                child: Text("请求超时,点击重试", style: TextStyle(color: highlightColor),),
              ),
            ),
          )
        )
      ],
    ),
  );

  /// 蒙版背景颜色
  ModelColor get shimmerBgColor => ModelColor(lightColor: const Color(0xffededed), darkColor: const Color(0xff111111));

  late final ValueNotifier<ModelColor> _shimmerBgColorNotifier = ValueNotifier<ModelColor>(shimmerBgColor);

  @override
  void dispose() {
    super.dispose();
    _shimmerBgColorNotifier.dispose();
  }

  void initSuccessListener(){}

  @override
  Widget build(BuildContext context) {
    initContextDate(context);
    Future.delayed(loadingTimeout, ()=>{
      if(!_isInitSuccess){
        // 超时错误页面
        if(context.mounted){
          setState(() {
            _isTimeout = true;
          })
        }
      }
    });
    if(_isTimeout) {
      return timeoutWidget;
    }
    return _isInitSuccess
        ? widgetBuild(context)
        : ValueListenableBuilder(
      valueListenable: _shimmerBgColorNotifier,
      builder: (context, value, _) =>shimmer,
    );
  }

  void initContextDate(context){
    _shimmerBgColorNotifier.value.model = PlatformUtils.getBrightness(context);
  }

  Widget widgetBuild(BuildContext context);

  @override
  void initState() {
    super.initState();
    _init();
  }

  void _init(){
    initData().then((value){
      setState(() {
        _isInitSuccess = true;
        initSuccessListener();
      });
    });
  }

  /// 数据初始化
  Future<void> initData() async {}

  /// 加载动画
  Widget get shimmer => Container(
    color: _shimmerBgColorNotifier.value.color,
    child: Shimmer.fromColors(
      baseColor: Colors.grey,
      highlightColor: const Color(0x9E9E9E28),
      child: Center(
        child: Text(
          loadingHintText,
          textAlign: TextAlign.center,
          style: loadingHintTextStyle,
        ),
      ),
    ),
  );
}

mixin ContextState<T extends StatefulWidget> on State<T> {

  Future<void> contextInitDate(BuildContext context) async {

  }

  @override
  Widget build(BuildContext context) {
    contextInitDate(context);
    return widgetBuild(context);
  }

  Widget widgetBuild(BuildContext context);

}

mixin AppBarMixin {

  /// appBar 的背景颜色
  Color? get appBarBgColor => null;
  /// AppBar 高度
  double get appBarHeight => 52.0;
  /// AppBar action
  List<Widget> get appBarActions => [];
  /// appBar title
  String get appBarTitle => "";

  double get elevation => 0.5;

  IconThemeData? get iconTheme => null;

  TextStyle? get appBarTitleStyle => const TextStyle(fontSize: 16);

  Widget? get leading => null;

  /// appBar
  PreferredSize get appBar => PreferredSize(
    preferredSize: Size.fromHeight(appBarHeight),
    child: AppBar(
      leading: leading,
      backgroundColor: appBarBgColor,
      title: Text(appBarTitle, style: appBarTitleStyle,),
      centerTitle: true,
      elevation: elevation,
      actions: appBarActions,
      iconTheme: iconTheme,
    ),
  );

}

abstract class AppBarState<T extends StatefulWidget> extends State<T> with AppBarMixin{

}

/// 明暗模式
mixin BrightnessModeState<T extends StatefulWidget> on State<T>{


  /// 需要动态切换的颜色
  List<ModelColor> get brightnessColors => [];

  void initModelColor(BuildContext context) async {
    setState(() {
      var brightness = PlatformUtils.getBrightness(context);
      for (var color in brightnessColors) {
        color.model = brightness;
      }
    });
  }

}

/// 明暗模式
mixin BrightnessMode{

  /// 需要动态切换的颜色
  List<ModelColor> get brightnessColors;

  void initModelColor(BuildContext context) async {
    var brightness = PlatformUtils.getBrightness(context);
    for (var color in brightnessColors) {
      color.model = brightness;
    }
  }

}

mixin AsyncState<T extends StatefulWidget> on State<T> {

  @override
  void initState(){
    asyncInitState();
    super.initState();
  }

  Future<void> asyncInitState();

}